package boardgamer.common;

import com.google.common.base.Objects;

import javax.annotation.Nullable;
import java.io.Serializable;

/**
 * Contains object to be used as a synchronized parameter. For example:
 * <p/>
 * <code>
 * SynchronizedObject<String> syncString = new SynchronizedObject<String>();
 * synchronized (syncString) {
 *   syncString.set("Blah");
 *   System.out.println(syncString.get());
 * }
 * </code>
 *
 * @author garysoed
 */
public class SynchronizedObject<T> implements Serializable {

  private static final long serialVersionUID = -1643166497312786489L;

  @Nullable
  private T object;

  public SynchronizedObject(T object) {
    this.object = object;
  }

  public SynchronizedObject() { }

  public T get() {
    return object;
  }

  public void set(T object) {
    this.object = object;
  }

  @SuppressWarnings("unchecked")
  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof SynchronizedObject<?>)) {
      return false;
    }

    SynchronizedObject<T> that = (SynchronizedObject<T>) obj;
    return this.object.equals(that.object);
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(object);
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this)
        .add("object", object)
        .toString();
  }
}
